<template>
  <div>
    <el-upload
        class="xxxx"
        :action="uploadUrl"
        list-type="picture-card"
        :auto-upload="true"
        :limit="limit"
        :data="extData"
        :multiple="true"
        v-model:file-list="fileList"
        :headers="headers"
        :before-upload="handleBeforeUpload"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove">
      <el-icon>
        <ele-Plus/>
      </el-icon>
    </el-upload>

    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%"/>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {defineComponent, onBeforeMount, ref, watch} from 'vue';
import type {UploadFile, UploadFiles, UploadRawFile} from 'element-plus'
import {Session} from "/@/utils/storage";
import {buildParamsSignStr, extractFileNameFromUrl} from "/@/utils/format";
import {ElMessage} from "element-plus";

const props = {
  defaultList: {
    type: Array,
    default() {
      return []
    }
  },
  limit: {
    required: true,
    type: Number
  },
  mode: {
    type: String,
    default() {
      return 'public'
    }
  },
  isCloud: {
    type: Number,
    default() {
      return 1
    }
  },
  saveFilePath: {
    type: String,
    default() {
      return ''
    }
  },
  saveName: {
    type: String,
    default() {
      return ''
    }
  },
  keepLocal: {
    type: Number,
    default() {
      return 1
    }
  },
  mimes: {
    type: Array,
    default() {
      return []
    }
  }
};
export default defineComponent({
  name: 'uploader',
  props: props,
  setup(props, {emit}) {
    const dialogImageUrl = ref('')
    const dialogVisible = ref(false)
    const disabled = ref(false)
    const headers = ref<Record<String, any>>({})
    const extData = ref()
    const fileList = ref([])
    const uploadUrl = ref("")
    onBeforeMount(() => {
      const baseUrl = "/api/v1/common/file/upload";
      uploadUrl.value = import.meta.env.MODE == 'production' ? import.meta.env.VITE_API_URL + baseUrl : '/AyLiRA3FY' + baseUrl;
      headers.value = {
        JToken: `${Session.get('token')}`,
        'X-App-Id': import.meta.env.VITE_APP_ID
      }
      let _ext = {}
      _ext.mode = props.mode
      if (props.isCloud > 0) _ext.isCloud = props.isCloud
      if (props.saveFilePath != '') _ext.saveFilePath = props.saveFilePath
      if (props.saveName != '') _ext.saveName = props.saveName
      if (props.keepLocal > 0) _ext.keepLocal = props.keepLocal
      extData.value = _ext
      fileList.value = props.defaultList
    });
    watch(
        () => props.defaultList,
        (newVal, oldVal) => {
          fileList.value = props.defaultList
        })
    const handleRemove = (file: UploadFile) => {
      // console.log(file)
    }

    const handlePictureCardPreview = (file: UploadFile) => {
      dialogImageUrl.value = file.url!
      dialogVisible.value = true
    }

    const handleDownload = (file: UploadFile) => {
      // console.log(file)
    }

    const handleOnSuccess = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
      console.log(response)
    }

    const handleBeforeUpload = (rawFile: UploadRawFile) => {
      if (props.mimes?.length > 0) {
        if (!props.mimes.includes(rawFile.type)) {
          ElMessage.error('上传文件格式错误');
          return false;
        }
      }
      let _ext = extData.value
      _ext._time = new Date().getTime()
      _ext.sign = buildParamsSignStr(_ext)
      extData.value = _ext
    }
    const getFileList = () => {
      console.log(fileList.value)
      const _list = [];
      if (fileList.value.length > 0) {
        fileList.value.forEach(item => {
          let _url = 'response' in item ? item.response.data.url : item.url
          let _name = extractFileNameFromUrl(_url);
          _list.push({
            name: _name || 'default',
            url: _url
          })
        })
      }
      return _list
    }
    return {
      uploadUrl,
      fileList,
      headers,
      extData,
      dialogImageUrl,
      dialogVisible,
      disabled,
      handleRemove,
      handlePictureCardPreview,
      handleDownload,
      handleBeforeUpload,
      handleOnSuccess,
      getFileList
    }
  }
});
</script>

<style scoped lang="scss">

</style>
